<template>
  <div style="width: 100%;height: 100%" class="wrapper">
    <button v-if="type>2" @click="back()" class="btn">返回上级</button>
    <div id="mapChart" style="width: 100%;height: 100%"></div>
  </div>
</template>

<script>
import cityMap from '../assets/js/china-main-city-map'
import echarts from 'echarts'
import axios from 'axios'

export default {
  name: 'chinaMap',
  data() {
    return {
      type: 2,
      myChart: null,
      // 中国地图（第一级地图）的ID、Name、Json数据
      // chinaId: 100000,
      chinaId: 450000,
      // chinaName: 'china',
      chinaName: '广西',
      chinaJson: null,
      // 记录父级ID、Name
      mapStack: [],
      parentId: null,
      parentName: null
    }
  },
  props: {
    msg: String,
    mapData: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  created: function () {
    this.mapChart('mapChart')
    window.addEventListener('resize', this.resizeChart)
  },
  destroyed() {
    window.removeEventListener('resize', this.resizeChart)
  },
  methods: {
    /**
     * 返回上一级地图
     */
    back() {
      if (this.mapStack.length !== 0) {
        // 如果有上级目录则执行
        // this.registerAndsetOption(this.myChart, this.chinaId, this.chinaName, this.chinaJson, false, this.type)
        // this.mapStack = []
        // this.parentId = this.chinaId
        // this.parentName = this.chinaName

        let map = this.mapStack.pop()
        console.log(map)
        this.type--
        if (this.type <= 2) {
          this.type = 2
        }
        axios
          .get('mapJson/map/' + map.mapId + '.json', {})
          .then(response => {
            const mapJson = response.data
            this.registerAndsetOption(
              this.myChart,
              map.mapId,
              map.mapName,
              mapJson,
              false,
              this.type
            )
            // 返回上一级后，父级的ID、Name随之改变
            this.parentId = map.mapId
            this.parentName = map.mapName
          })
      }
    },
    /**
     * Echarts地图
     */
    mapChart(divid) {
      axios.get('mapJson/map/' + this.chinaId + '.json', {}).then(response => {
        const mapJson = response.data
        this.chinaJson = mapJson
        this.myChart = echarts.init(document.getElementById(divid))
        // 省级地图
        this.registerAndsetOption(this.myChart, this.chinaId, this.chinaName, mapJson, false, this.type)
        this.parentId = this.chinaId
        this.parentName = '广西'
        // 地图点击事件
        this.myChart.on('click', (param) => {
          let cityId = cityMap[param.name]
          console.log(param.name)
          console.log('cityId' + cityId)
          if (cityId) {
            this.type++
            if (this.type > 3) {
              this.type = 3
            }
            console.log(this.type)
            // 代表有下级地图
            axios
              .get('mapJson/map/' + cityId + '.json', {})
              .then(response => {
                const mapJson = response.data
                this.registerAndsetOption(
                  this.myChart,
                  cityId,
                  param.name,
                  mapJson,
                  true,
                  this.type
                )
              })
          } else {
            this.backClick = 0
            this.type = 2
            // 没有下级地图，回到一级中国地图，并将mapStack清空
            this.registerAndsetOption(this.myChart, this.chinaId, this.chinaName, this.chinaJson, false, this.type)
            this.mapStack = []
            this.parentId = this.chinaId
            this.parentName = this.chinaName
          }
        })
      })
    },
    resizeChart() {
      this.myChart ? this.myChart.resize() : ''
    },
    // type规定省市区的数据 1:省 2：市 3：县
    /**
     *
     * @param {*} myChart
     * @param {*} id        省市县Id
     * @param {*} name      省市县名称
     * @param {*} mapJson   地图Json数据
     * @param {*} flag      是否往mapStack里添加parentId，parentName
     */
    registerAndsetOption(myChart, id, name, mapJson, flag, type) {
      echarts.registerMap(name, mapJson)
      myChart.setOption({
        tooltip: {
          // trigger: 'axis'
          show: true,
          formatter: function (params) {
            return `${params.name}:${params.value || 0}(亩)`
          }
        },
        series: [
          {
            type: 'map',
            map: name,
            // zoom: 1, // 当前视角的缩放比例
            // roam: true, // 是否开启平游或缩放
            itemStyle: {
              // normal: {
              //   areaColor: 'rgba(23, 27, 57,0)',
              //   borderColor: '#1dc199',
              //   borderWidth: 1
              // },
              normal: {
                areaColor: 'rgba(23, 27, 57,0)',
                borderColor: '#1dc199',
                borderWidth: 1
              },
              emphasis: {
                areaColor: '#21AEF8'
              }
            },
            data: this.initMapData(mapJson, type)
          }
        ]
      })
      if (flag) {
        console.log(this.mapStack)
        // 往mapStack里添加parentId，parentName,返回上一级使用
        this.mapStack.push({
          mapId: this.parentId,
          mapName: this.parentName
        })
        this.parentId = id
        this.parentName = name
      }
    },
    // type规定省市区的数据 1:省 2：市 3：县
    initMapData(mapJson, type) {
      // console.log(type)
      let mapData = []
      let mapType = ['', this.mapData.provinceTotalData, this.mapData.cityTotalData, this.mapData.countyTotalData]
      for (let i = 0; i < mapJson.features.length; i++) {
        for (let j = 0; j < mapType[type].length; j++) {
          // if (mapType[type][j][0].indexOf(mapJson.features[i].properties.name) !== -1) {
          //   mapData.push({
          //     name: mapJson.features[i].properties.name,
          //     value: mapType[type][j][1]
          //   })
          // } else {
          //   mapData.push({
          //     name: mapJson.features[i].properties.name,
          //     value: 0
          //   })
          // }
          if (type === 2) {
            mapData = [
              {
                name: '南宁市',
                value: 4293.2,
                selected: true
              },
              {
                name: '百色市',
                value: 3541.5,
                selected: true
              },
              {
                name: '柳州市',
                value: 1306.6,
                selected: true
              }
            ]
          } else {
            mapData.push({
              name: mapJson.features[i].properties.name,
              value: 0
            })
          }
        }
      }
      return mapData
    }
  },
  watch: {
    mapData: {
      handler: function () {

      },
      deep: true
    }
  }
}
</script>

<style>
  body {
    /*background-image: url("../../assets/beijingtupian.png");*/
  }
</style>

<style scoped>
  .wrapper {
    height: 100%;
    width: 100%;
    position: relative;
  }

  .btn {
    z-index: 9999;
    position: absolute;
    top: 0;
    left: 0;
    cursor: pointer;
    border: none;
    padding: 10px;
    font-size: 16px;
    font-weight: 400;
    background: rgba(14, 107, 183, 0.9);
    border-radius: 5px;
    color: #00ffff;
  }
</style>
